package com.example.forum.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import com.example.forum.commons.tools.StringUtil;
import com.example.forum.commons.tools.Transfer.DataTransfer;
import com.example.forum.entity.TSensitivewords;
import com.example.forum.entity.TUsers;
import com.example.forum.service.ITSensitivewordsService;
import com.example.forum.service.ITUsersService;
import com.example.forum.vo.ImportFileReturnDto;
import com.example.forum.vo.JsonResult;
import com.example.forum.vo.PageDto;
import com.example.forum.vo.SenctiveWordsDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author why
 * @since 2020-04-22
 */
@RestController
@RequestMapping("SensitiveWords")
public class TSensitivewordsController extends BaseController{

    @Autowired
    private ITSensitivewordsService sensitivewordsService;

    @Autowired
    private DataTransfer dataTransfer;

    @Autowired
    private ITUsersService usersService;

    /**
     *  根据过滤条件查询敏感词分页
     * @param type
     * @param sensitiveWordsName
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("GetSensitiveWordsPaged")
    public JsonResult GetSensitiveWordsPaged(@RequestParam(value = "type", required = false) Boolean type,
                                             @RequestParam(value = "SensitiveWordsName", required = false) String sensitiveWordsName,
                                             @RequestParam(defaultValue = "0", value = "pageIndex") Integer pageIndex,
                                             @RequestParam(defaultValue = "10", value = "pageSize") Integer pageSize) {
        ArrayList<SenctiveWordsDto> senctiveWordsDtoList = new ArrayList<>();

        if (StringUtil.isEmpty(sensitiveWordsName) && type == null) {
            IPage<TSensitivewords> page = sensitivewordsService.page(new Page<TSensitivewords>(pageIndex, pageSize),
                    new QueryWrapper<TSensitivewords>().eq("IsDeleted", 0));

            getSenctiveDto(senctiveWordsDtoList, page);

            return new JsonResult(HttpStatus.OK, "成功", new PageDto(page.getTotal(), senctiveWordsDtoList));
        }
        //关键字为空时 type 不空 查询
        if (StringUtil.isEmpty(sensitiveWordsName) && type != null) {
            //true  放行的词
            if (type) {
                IPage<TSensitivewords> page = sensitivewordsService.page(new Page<TSensitivewords>(pageIndex, pageSize),
                        new QueryWrapper<TSensitivewords>()
                                .eq("IsDeleted", 0)
                                .eq("isRelease", 0));

                getSenctiveDto(senctiveWordsDtoList, page);
                return new JsonResult(HttpStatus.OK, "成功", new PageDto(page.getTotal(), senctiveWordsDtoList));

            } else {
                //未放行
                IPage<TSensitivewords> page = sensitivewordsService.page(new Page<TSensitivewords>(pageIndex, pageSize),
                        new QueryWrapper<TSensitivewords>()
                                .eq("IsDeleted", 0)
                                .eq("isRelease", 1));
                getSenctiveDto(senctiveWordsDtoList, page);
                return new JsonResult(HttpStatus.OK, "成功", new PageDto(page.getTotal(), senctiveWordsDtoList));
            }
        } else {
            //不为空时直接分页查询
            IPage<TSensitivewords> page = sensitivewordsService.page(new Page<TSensitivewords>(pageIndex, pageSize),
                    new QueryWrapper<TSensitivewords>()
                            .eq("IsDeleted", 0)
                            .like("terms", "%" + sensitiveWordsName + "%"));
            getSenctiveDto(senctiveWordsDtoList, page);
            return new JsonResult(HttpStatus.OK, "成功", new PageDto(page.getTotal(), senctiveWordsDtoList));
        }
    }
    
    //封装获取dto
    private void getSenctiveDto(ArrayList<SenctiveWordsDto> senctiveWordsDtoList, IPage<TSensitivewords> page) {

        for (TSensitivewords item : page.getRecords()) {
            SenctiveWordsDto senctiveWordsDto = new SenctiveWordsDto();
            senctiveWordsDto.setId(item.getId());
            senctiveWordsDto.setTerms(item.getTerms());
            senctiveWordsDto.setLevel(item.getLevel());
            senctiveWordsDto.setIsrelease(item.getIsrelease());
            senctiveWordsDtoList.add(senctiveWordsDto);
        }
    }

    /**
     * 添加敏感词
     * @param senctiveWordsDto
     * @return
     */
    @PostMapping("AddOrUpdateSensitiveWords")
    public JsonResult AddOrUpdateSensitiveWords(@RequestBody SenctiveWordsDto senctiveWordsDto){

        if (StringUtil.isEmpty(senctiveWordsDto.getTerms())) {
            return new JsonResult(HttpStatus.BAD_REQUEST,"数据为空",null);
        }
         //根据terms获取后台是否存在
         TSensitivewords trems = sensitivewordsService.getOne(new QueryWrapper<TSensitivewords>().eq("terms", senctiveWordsDto.getTerms()));
        //QueryChainWrapper<TSensitivewords> trems = sensitivewordsService.query().eq("terms", senctiveWordsDto.getTerms());
         if (trems!=null) {
             return new JsonResult(HttpStatus.BAD_REQUEST,"数据已经存在",null);
         }
         String currentUserId = currentUserId();
         TSensitivewords tSensitivewords = new TSensitivewords();
         tSensitivewords.setCreatoruserid(currentUserId);
         tSensitivewords.setLevel(0);
         tSensitivewords.setIsrelease(true);
         tSensitivewords.setIsdeleted(false);
         tSensitivewords.setTerms(senctiveWordsDto.getTerms());

         if (sensitivewordsService.insertTSensitiveWords(tSensitivewords)) {
             return new JsonResult(HttpStatus.OK,"添加成功",null);
         }
         return new JsonResult(HttpStatus.BAD_REQUEST,"添加失败",null);
    }

    /**
     * IsRelease true 放行
     * <param name="wordIds">敏感词Ids  List格式</param>
     *  <param name="IsRelease">是否放行</param>
     * @param senctiveWordsDto
     * @return
     */
    @PostMapping("UpdateIsRelease")
    public JsonResult updateIsRelease(@RequestBody SenctiveWordsDto senctiveWordsDto){

        TUsers users = usersService.getOne(new QueryWrapper<TUsers>().eq("id", currentUserId()).eq("IsDeleted", 0));
        if (users==null) {
            return new JsonResult(HttpStatus.BAD_REQUEST,"该用户不存在",null);
        }

        List<String> wordIds = senctiveWordsDto.getWordIds();
        for (String wordId :wordIds){
           TSensitivewords eq = sensitivewordsService.getOne(new QueryWrapper<TSensitivewords>().eq("IsDeleted", 0).eq("Id", wordId));
           if (eq==null) {
               return new JsonResult(HttpStatus.BAD_REQUEST,"改敏感词不存在",null);
           }
           eq.setCreatoruserid(currentUserId());
           eq.setIsrelease(senctiveWordsDto.getIsrelease());
           sensitivewordsService.updateById(eq);
        }
        return new JsonResult(HttpStatus.OK,"更新成功",null);
    }

    /**
     * \删除敏感词
     * <param name="wordsIds">id集合</param>
     *  <param name="isDeleted">是否删除  true 1</param>
     * @param senctiveWordsDto
     * @return
     */
     @PostMapping("DeleteSensitiveWords")
      public JsonResult deleteSensitiveWords(@RequestBody SenctiveWordsDto senctiveWordsDto){

         //删除失败
         if (!sensitivewordsService.deleteSensitiveWords(senctiveWordsDto,currentUserId())) {
             return new JsonResult(HttpStatus.BAD_REQUEST,"删除失败",null);
         }
         return new JsonResult(HttpStatus.OK,"删除成功",null);
      }


    /**
     * 敏感词批量导入
     * @param file
     * @return
     */
    @PostMapping("ImportSensitiveWords")
    public JsonResult importSensitiveWords(@RequestParam("importfile") MultipartFile file){

        TUsers users = usersService.getOne(new QueryWrapper<TUsers>().eq("id", currentUserId()).eq("IsDeleted", 0));
        if (users==null) {
            return new JsonResult(HttpStatus.BAD_REQUEST,"该用户不存在",null);
        }

        //返回 操作信息 String  是否成功 true
        ImportFileReturnDto importFileReturnDto = sensitivewordsService.importExcel(file,currentUserId());

        if (importFileReturnDto.getStatus()) {

        return new JsonResult(HttpStatus.OK,importFileReturnDto.getMessage(),null);
        }
        return new JsonResult(HttpStatus.BAD_REQUEST,importFileReturnDto.getMessage(),null);
    }
}
